package com.examlpe.lotterysystem.service.Impl;

import com.examlpe.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.examlpe.lotterysystem.common.exception.ServiceException;
import com.examlpe.lotterysystem.common.utils.*;
import com.examlpe.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    //对应redis里的key要标准化：为了区分业务，应该给key定义前缀：VerificationCode_手机号,User_手机号
    private static final String VERIFICATIONCODE_CODE_PREFIX = "VERIFICATIONCODE_CODE_";
    private static final Long VERIFICATIONCODE_CODE_TIMEOUT = 60L;
    private static final String VERIFICATIONCODE_CODE_TEMPLATE_CODE = "SMS_478580116";
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
        //校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //生成随机验证码
        String captcha = CaptchaUtil.getCaptchaUtil(4);
        //发送验证码
        //{"code":"xxxx"}
        Map<String,String> map = new HashMap<>();
        map.put("code",captcha);
        smsUtil.sendMessage(VERIFICATIONCODE_CODE_TEMPLATE_CODE,phoneNumber, JacksonUtil.writeValueAsString(map));
        //缓存验证码
        //一个手机号对应一个验证码
        redisUtil.set(VERIFICATIONCODE_CODE_PREFIX+phoneNumber,captcha,VERIFICATIONCODE_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATIONCODE_CODE_PREFIX+phoneNumber);
    }
}
